package com.zhao.blog.service;

import com.zhao.blog.NotFoundException;
import com.zhao.blog.dao.TagDao;
import com.zhao.blog.pojo.Tag;
import com.zhao.blog.pojo.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoZhao
 * @date 2022/1/6
 * @describe
 */
@Service
public class TagServiceImpl implements TagService {
   @Autowired
   private TagDao tagDao;

   @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagDao.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagDao.findById(id).get();
    }

    @Transactional
    @Override
    public Page<Tag> listTags(Pageable pageable) {
        return tagDao.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagDao.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagDao.findAllById(convertToList(ids));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Pageable pageable=PageRequest.of(0, size,Sort.by(Sort.Direction.DESC,"blogs.size"));
        return tagDao.findTop(pageable);
    }

    private List<Long> convertToList(String ids){
       List<Long> list=new ArrayList<>();
       if (!"".equals(ids) && ids !=null){
           String[] idArray=ids.split(",");
           for (int i=0;i<idArray.length;i++){
               list.add(new Long(idArray[i]));
           }
       }
       return list;
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
       Tag t = tagDao.findById(id).get();
        if (t == null){
            throw new NotFoundException("不存在该标签");
        }
        BeanUtils.copyProperties(tag,t);
        return tagDao.save(t);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagDao.deleteById(id);
    }
}
